import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class MyCache {

    public static void main(String[] args) {
        MyCache cache = new MyCache();
        for (int i = 0; i < 10; i++) {
            final int j = i;
            new Thread(() -> {
                cache.put(j + "", j + "1");
            }, "t" + i).start();
        }
        for (int i = 0; i < 10; i++) {
            final int j = i;
            new Thread(() -> {
                cache.get(j + "", j + "1");
            }, "t" + i).start();
        }
        cache.clear();
    }


    private volatile Map<String, Object> map = new HashMap<>();

    private ReadWriteLock lock = new ReentrantReadWriteLock();

    public void put(String key, Object value) {
        lock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + " 正在写入：" + key);
            map.put(key, value);
            TimeUnit.MILLISECONDS.sleep(1000);
            System.out.println(Thread.currentThread().getName() + " 写入完成");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.writeLock().unlock();
        }
    }

    public void get(String key, Object value) {
        lock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + " 正在读取：" + key);
            map.put(key, value);
            TimeUnit.MILLISECONDS.sleep(1000);
            System.out.println(Thread.currentThread().getName() + " 读取完成");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.readLock().unlock();
        }
    }

    public void clear() {
        map.clear();
    }
}
